import { SyncOutlined } from '@ant-design/icons'
import { Button, App, Spin } from 'antd'
import { CoverPanel } from '@/desktop/views/app/cover-panel'
import { Detail } from '../detail'
import { Edit } from '../edit'
import { getTasks, type Task, useSearch } from '../logics'
import { SearchForm } from './search'
import { TasksTable } from './table'

export function BatchMessage() {
  const [editing, setEditing] = useState<Task | true | null>(null)
  const [showDetail, setShowDetail] = useState<Task | null>(null)
  return editing !== null ? (
    <Edit task={editing} onClose={() => setEditing(null)} />
  ) : showDetail !== null ? (
    <Detail
      task={showDetail}
      onClose={() => setShowDetail(null)}
      edit={() => setEditing(showDetail)}
    />
  ) : (
    <List edit={setEditing} showDetail={setShowDetail} />
  )
}

function List({
  edit,
  showDetail,
}: {
  edit: (task: Task | true) => void
  showDetail: (task: Task) => void
}) {
  const { message } = App.useApp()

  const [allTasks, setAllTasks] = useState<Task[] | null>(null)
  const [loading, setLoading] = useState(false)
  const load = useCallback(async () => {
    setLoading(true)
    const res = await getTasks()
    setLoading(false)
    if (res.success) {
      setAllTasks(res.data)
    } else {
      void message.warning('任务列表加载失败')
      setAllTasks([])
    }
  }, [message])
  useEffect(() => {
    void load()
    const intervalId = setInterval(load, 10 * 1000)
    return () => clearInterval(intervalId)
  }, [load])

  const { tasks, search, setSearch } = useSearch(allTasks)

  return <CoverPanel title="批量发消息">
    <Spin spinning={allTasks === null}>
      <div css={s.wrap}>
        <header>
          <Button type="primary" onClick={() => edit(true)}>
            创建群发任务
          </Button>
          <Button type="link" icon={<SyncOutlined />} loading={loading} onClick={load}>
            刷新
          </Button>
        </header>

        <SearchForm search={search} setSearch={setSearch} />
        <TasksTable tasks={tasks} reload={load} edit={edit} showDetail={showDetail} />
      </div>
    </Spin>
  </CoverPanel>
}

const s = {
  wrap: css`
    min-height: 300px;
    padding-top: 20px;
    & > header {
      margin-bottom: 20px;
    }
  `,
}
